//! 客户服务
//! 提供客户关系管理相关的业务逻辑

use crate::client::EntityClient;
use crate::models::party::*;
use crate::models::party_relationship::*;
use crate::models::view_entities::*;
use crate::models::*;
use crate::services::{QueryBuilder, PagedResult, utils};
use crate::{Result, PartyModError};
use std::collections::HashMap;
use chrono::{DateTime, Utc};

/// 客户服务
#[derive(Clone)]
pub struct CustomerService {
    client: EntityClient,
}

/// 客户信息
#[derive(Debug, Clone)]
pub struct Customer {
    pub party_id: String,
    pub customer_type: CustomerType,
    pub status: CustomerStatus,
    pub created_date: DateTime<Utc>,
    pub first_contact_date: Option<DateTime<Utc>>,
    pub last_contact_date: Option<DateTime<Utc>>,
    pub assigned_sales_rep: Option<String>,
    pub customer_value: Option<f64>,
    pub credit_limit: Option<f64>,
    // 个人客户信息
    pub first_name: Option<String>,
    pub last_name: Option<String>,
    pub email: Option<String>,
    pub phone: Option<String>,
    // 企业客户信息
    pub company_name: Option<String>,
    pub industry: Option<String>,
    pub annual_revenue: Option<f64>,
    pub num_employees: Option<i64>,
}

/// 客户类型
#[derive(Debug, Clone, PartialEq)]
pub enum CustomerType {
    Individual,  // 个人客户
    Business,    // 企业客户
}

/// 客户状态
#[derive(Debug, Clone, PartialEq)]
pub enum CustomerStatus {
    Prospect,    // 潜在客户
    Lead,        // 线索
    Active,      // 活跃客户
    Inactive,    // 非活跃客户
    Lost,        // 流失客户
}

/// 销售代表客户列表
#[derive(Debug, Clone)]
pub struct SalesRepCustomer {
    pub sales_rep_id: String,
    pub sales_rep_name: String,
    pub customer_id: String,
    pub customer_name: String,
    pub customer_type: CustomerType,
    pub relationship_start_date: DateTime<Utc>,
    pub last_contact_date: Option<DateTime<Utc>>,
    pub customer_value: Option<f64>,
    pub status: CustomerStatus,
}

/// 客户转换记录
#[derive(Debug, Clone)]
pub struct CustomerConversion {
    pub customer_id: String,
    pub from_status: CustomerStatus,
    pub to_status: CustomerStatus,
    pub conversion_date: DateTime<Utc>,
    pub converted_by: Option<String>,
    pub notes: Option<String>,
}

impl CustomerService {
    /// 创建新的客户服务
    pub fn new(client: EntityClient) -> Self {
        Self { client }
    }

    /// 创建个人客户
    pub async fn create_individual_customer(
        &mut self,
        first_name: &str,
        last_name: &str,
        email: Option<&str>,
        phone: Option<&str>,
        assigned_sales_rep: Option<&str>
    ) -> Result<String> {
        let party_id = utils::generate_party_id();
        
        // 创建Person
        let person = Person {
            party_id: party_id.clone(),
            salutation: None,
            first_name: Some(first_name.to_string()),
            middle_name: None,
            last_name: Some(last_name.to_string()),
            personal_title: None,
            suffix: None,
            nickname: None,
            first_name_local: None,
            middle_name_local: None,
            last_name_local: None,
            other_local: None,
            member_id: None,
            gender: None,
            birth_date: None,
            deceased_date: None,
            height: None,
            weight: None,
            mothers_maiden_name: None,
            marital_status_enum_id: None,
            social_security_number: None,
            passport_number: None,
            passport_expire_date: None,
            total_years_work_experience: None,
            comments: None,
            employment_status_enum_id: None,
            residence_status_enum_id: None,
            occupation: None,
            years_with_employer: None,
            months_with_employer: None,
            existing_customer: Some(true),
            card_id: None,
        };
        
        // 创建Party
        let party = Party {
            party_id: party_id.clone(),
            party_type_id: "PERSON".to_string(),
            external_id: None,
            preferred_currency_uom_id: None,
            description: Some(format!("{} {}", first_name, last_name)),
            status_id: Some("PARTY_ENABLED".to_string()),
            created_date: Some(Utc::now()),
            created_by_user_login: None,
            last_modified_date: Some(Utc::now()),
            last_modified_by_user_login: None,
            data_source_id: None,
            is_unread: Some(false),
        };
        
        // 插入Party数据
        let party_data = party.to_data_row();
        self.client.insert_data("Party", party_data).await?;
        
        // 插入Person数据
        let person_data = person.to_data_row();
        self.client.insert_data("Person", person_data).await?;
        
        // 添加客户角色
        let customer_role = PartyRole {
            party_id: party_id.clone(),
            role_type_id: "CUSTOMER".to_string(),
        };
        let role_data = customer_role.to_data_row();
        self.client.insert_data("PartyRole", role_data).await?;
        
        // 如果指定了销售代表，创建客户关系
        if let Some(sales_rep_id) = assigned_sales_rep {
            self.assign_sales_rep(&party_id, sales_rep_id).await?;
        }
        
        // 添加联系方式
        if let Some(_email_addr) = email {
            // TODO: 添加邮箱联系方式
        }
        
        if let Some(_phone_num) = phone {
            // TODO: 添加电话联系方式
        }
        
        Ok(party_id)
    }

    /// 创建企业客户
    pub async fn create_business_customer(
        &mut self,
        company_name: &str,
        industry: Option<&str>,
        annual_revenue: Option<f64>,
        num_employees: Option<i64>,
        assigned_sales_rep: Option<&str>
    ) -> Result<String> {
        let party_id = utils::generate_party_id();
        
        // 创建PartyGroup
        let party_group = PartyGroup {
            party_id: party_id.clone(),
            group_name: Some(company_name.to_string()),
            group_name_local: None,
            office_site_name: None,
            annual_revenue,
            num_employees,
            ticker_symbol: None,
            comments: industry.map(|s| format!("Industry: {}", s)),
            logo_image_url: None,
        };
        
        // 创建Party
        let party = Party {
            party_id: party_id.clone(),
            party_type_id: "PARTY_GROUP".to_string(),
            external_id: None,
            preferred_currency_uom_id: None,
            description: Some(company_name.to_string()),
            status_id: Some("PARTY_ENABLED".to_string()),
            created_date: Some(Utc::now()),
            created_by_user_login: None,
            last_modified_date: Some(Utc::now()),
            last_modified_by_user_login: None,
            data_source_id: None,
            is_unread: Some(false),
        };
        
        // 插入Party数据
        let party_data = party.to_data_row();
        self.client.insert_data("Party", party_data).await?;
        
        // 插入PartyGroup数据
        let group_data = party_group.to_data_row();
        self.client.insert_data("PartyGroup", group_data).await?;
        
        // 添加客户角色
        let customer_role = PartyRole {
            party_id: party_id.clone(),
            role_type_id: "CUSTOMER".to_string(),
        };
        let role_data = customer_role.to_data_row();
        self.client.insert_data("PartyRole", role_data).await?;
        
        // 如果指定了销售代表，创建客户关系
        if let Some(sales_rep_id) = assigned_sales_rep {
            self.assign_sales_rep(&party_id, sales_rep_id).await?;
        }
        
        Ok(party_id)
    }

    /// 分配销售代表
    pub async fn assign_sales_rep(&mut self, customer_id: &str, sales_rep_id: &str) -> Result<()> {
        // 确保销售代表有相应的角色
        let sales_role = PartyRole {
            party_id: sales_rep_id.to_string(),
            role_type_id: "SALES_REP".to_string(),
        };
        
        let role_data = sales_role.to_data_row();
        
        // 尝试插入角色（如果已存在会失败，但不影响后续操作）
        let _ = self.client.insert_data("PartyRole", role_data).await;
        
        // 创建销售代表-客户关系
        let relationship = PartyRelationship {
            party_id_from: sales_rep_id.to_string(),
            party_id_to: customer_id.to_string(),
            role_type_id_from: "SALES_REP".to_string(),
            role_type_id_to: "CUSTOMER".to_string(),
            from_date: Utc::now(),
            thru_date: None,
            status_id: Some("PARTY_RELATIONSHIP_ACTIVE".to_string()),
            relationship_name: Some("Sales Representative".to_string()),
            security_group_id: None,
            priority_type_id: None,
            party_relationship_type_id: Some("SALES_AFFILIATE".to_string()),
            permissions_enum_id: None,
            position_title: Some("Sales Representative".to_string()),
            comments: None,
        };
        
        let data = relationship.to_data_row();
        
        self.client.insert_data("PartyRelationship", data).await?;
        Ok(())
    }

    /// 获取销售代表的客户列表
    pub async fn get_sales_rep_customers(&mut self, sales_rep_id: &str) -> Result<Vec<SalesRepCustomer>> {
        let conditions = vec![
            crate::models::QueryCondition {
                field: "partyIdFrom".to_string(),
                operator: "EQUALS".to_string(),
                value: sales_rep_id.to_string(),
                logic: "AND".to_string(),
            },
            crate::models::QueryCondition {
                field: "roleTypeIdFrom".to_string(),
                operator: "EQUALS".to_string(),
                value: "SALES_REP".to_string(),
                logic: "AND".to_string(),
            },
            crate::models::QueryCondition {
                field: "roleTypeIdTo".to_string(),
                operator: "EQUALS".to_string(),
                value: "CUSTOMER".to_string(),
                logic: "AND".to_string(),
            }
        ];
        
        let response = self.client.query_data("PartyRelationship", None, Some(conditions), None, None, None).await?;
        
        let mut customers = Vec::new();
        for row in response {
            let relationship = PartyRelationship::from_data_row(&row.fields)?;
            
            // 需要额外查询Party信息来获取party_type_id
            let customer_type = CustomerType::Individual; // 默认为个人，实际应查询Party表
            
            let customer_name = "Unknown".to_string(); // 需要额外查询Person或PartyGroup表
            let sales_rep_name = "Unknown".to_string(); // 需要额外查询Person表
            
            let customer = SalesRepCustomer {
                sales_rep_id: relationship.party_id_from,
                sales_rep_name,
                customer_id: relationship.party_id_to,
                customer_name,
                customer_type,
                relationship_start_date: relationship.from_date,
                last_contact_date: None, // 需要额外查询
                customer_value: None,    // 需要额外查询
                status: CustomerStatus::Active, // 默认状态
            };
            
            customers.push(customer);
        }
        
        Ok(customers)
    }

    /// 获取活跃客户列表
    pub async fn get_active_customers(&mut self) -> Result<Vec<Customer>> {
        let conditions = vec![
            crate::models::QueryCondition {
                field: "roleTypeId".to_string(),
                operator: "EQUALS".to_string(),
                value: "CUSTOMER".to_string(),
                logic: "AND".to_string(),
            }
        ];
        
        let response = self.client.query_data("PartyRole", None, Some(conditions), None, None, None).await?;
        
        let mut customers = Vec::new();
        for row in response {
            let party_role = PartyRole::from_data_row(&row.fields)?;
            
            // 获取Party详细信息
            if let Some(customer) = self.get_customer_details(&party_role.party_id).await? {
                customers.push(customer);
            }
        }
        
        Ok(customers)
    }

    /// 获取客户详细信息
    async fn get_customer_details(&mut self, party_id: &str) -> Result<Option<Customer>> {
        // 首先获取Party信息
        let conditions = vec![
            crate::models::QueryCondition {
                field: "partyId".to_string(),
                operator: "EQUALS".to_string(),
                value: party_id.to_string(),
                logic: "AND".to_string(),
            }
        ];
        
        let party_response = self.client.query_data("Party", None, Some(conditions), None, None, None).await?;
        
        if let Some(party_row) = party_response.first() {
            let party = Party::from_data_row(&party_row.fields)?;
            
            let customer_type = if party.party_type_id == "PERSON" {
                CustomerType::Individual
            } else {
                CustomerType::Business
            };
            
            let mut customer = Customer {
                party_id: party.party_id.clone(),
                customer_type: customer_type.clone(),
                status: CustomerStatus::Active, // 默认状态
                created_date: party.created_date.unwrap_or_else(Utc::now),
                first_contact_date: None,
                last_contact_date: None,
                assigned_sales_rep: None,
                customer_value: None,
                credit_limit: None,
                first_name: None,
                last_name: None,
                email: None,
                phone: None,
                company_name: None,
                industry: None,
                annual_revenue: None,
                num_employees: None,
            };
            
            // 根据客户类型获取详细信息
            if customer_type == CustomerType::Individual {
                // 获取个人信息
                let person_query = QueryBuilder::new()
                    .eq("partyId", party_id)
                    .build();
                
                let person_conditions = person_query.conditions.clone();
                
                let person_response = self.client.query_data(
                    "Person",
                    None,
                    Some(person_conditions),
                    None,
                    None,
                    None
                ).await?;
                
                if let Some(person_row) = person_response.first() {
                    let person = Person::from_data_row(&person_row.fields)?;
                    customer.first_name = person.first_name;
                    customer.last_name = person.last_name;
                }
            } else {
                // 获取企业信息
                let group_query = QueryBuilder::new()
                    .eq("partyId", party_id)
                    .build();
                
                let group_conditions = group_query.conditions.clone();
                
                let group_response = self.client.query_data(
                    "PartyGroup",
                    None,
                    Some(group_conditions),
                    None,
                    None,
                    None
                ).await?;
                
                if let Some(group_row) = group_response.first() {
                    let party_group = PartyGroup::from_data_row(&group_row.fields)?;
                    customer.company_name = party_group.group_name;
                    customer.annual_revenue = party_group.annual_revenue;
                    customer.num_employees = party_group.num_employees;
                }
            }
            
            Ok(Some(customer))
        } else {
            Ok(None)
        }
    }

    /// 转换潜在客户为正式客户
    pub async fn convert_prospect_to_customer(
        &mut self,
        prospect_id: &str,
        converted_by: Option<&str>,
        notes: Option<&str>
    ) -> Result<CustomerConversion> {
        // 这里可以添加更复杂的转换逻辑
        // 比如更新客户状态、记录转换历史等
        
        let conversion = CustomerConversion {
            customer_id: prospect_id.to_string(),
            from_status: CustomerStatus::Prospect,
            to_status: CustomerStatus::Active,
            conversion_date: Utc::now(),
            converted_by: converted_by.map(|s| s.to_string()),
            notes: notes.map(|s| s.to_string()),
        };
        
        // TODO: 在实际应用中，这里应该记录到数据库中
        // 可能需要创建一个CustomerConversion实体
        
        Ok(conversion)
    }

    /// 搜索客户
    pub async fn search_customers(&mut self, keyword: &str) -> Result<Vec<Customer>> {
        // 搜索个人客户
        let person_query = QueryBuilder::new()
            .like("firstName", keyword)
            .build();
        
        let person_response = self.client.query_data(
            "PartyAndPerson",
            None,
            Some(person_query.conditions),
            None,
            person_query.limit,
            person_query.offset
        ).await?;
        
        let mut customers = Vec::new();
        
        // 处理个人客户搜索结果
        for row in person_response {
            let party_and_person = PartyAndPerson::from_data_row(&row.fields)?;
            
            // 检查是否有客户角色
            if self.has_customer_role(&party_and_person.party_id).await? {
                let customer = Customer {
                    party_id: party_and_person.party_id,
                    customer_type: CustomerType::Individual,
                    status: CustomerStatus::Active,
                    created_date: party_and_person.created_date.unwrap_or_else(Utc::now),
                    first_contact_date: None,
                    last_contact_date: None,
                    assigned_sales_rep: None,
                    customer_value: None,
                    credit_limit: None,
                    first_name: party_and_person.first_name,
                    last_name: party_and_person.last_name,
                    email: None,
                    phone: None,
                    company_name: None,
                    industry: None,
                    annual_revenue: None,
                    num_employees: None,
                };
                customers.push(customer);
            }
        }
        
        // 搜索企业客户
        let group_query = QueryBuilder::new()
            .like("groupName", keyword)
            .build();
        
        let group_response = self.client.query_data(
            "PartyAndGroup",
            None,
            Some(group_query.conditions),
            None,
            group_query.limit,
            group_query.offset
        ).await?;
        
        // 处理企业客户搜索结果
        for row in group_response {
            let party_and_group = PartyAndGroup::from_data_row(&row.fields)?;
            
            // 检查是否有客户角色
            if self.has_customer_role(&party_and_group.party_id).await? {
                let customer = Customer {
                    party_id: party_and_group.party_id,
                    customer_type: CustomerType::Business,
                    status: CustomerStatus::Active,
                    created_date: party_and_group.created_date.unwrap_or_else(Utc::now),
                    first_contact_date: None,
                    last_contact_date: None,
                    assigned_sales_rep: None,
                    customer_value: None,
                    credit_limit: None,
                    first_name: None,
                    last_name: None,
                    email: None,
                    phone: None,
                    company_name: party_and_group.group_name,
                    industry: None,
                    annual_revenue: party_and_group.annual_revenue,
                    num_employees: party_and_group.num_employees,
                };
                customers.push(customer);
            }
        }
        
        Ok(customers)
    }

    /// 检查Party是否有客户角色
    async fn has_customer_role(&mut self, party_id: &str) -> Result<bool> {
        let query = QueryBuilder::new()
            .eq("partyId", party_id)
            .eq("roleTypeId", "CUSTOMER")
            .build();
        
        let response = self.client.query_data(
            "PartyRole",
            None,
            Some(query.conditions),
            None,
            None,
            None
        ).await?;
        Ok(!response.is_empty())
    }

    /// 更新客户信息
    pub async fn update_customer(&mut self, customer: &Customer) -> Result<()> {
        // 更新Party信息
        let party_query = QueryBuilder::new()
            .eq("partyId", &customer.party_id)
            .build();
        
        let party_response = self.client.query_data(
            "Party",
            None,
            Some(party_query.conditions),
            None,
            None,
            None
        ).await?;
        
        if let Some(party_row) = party_response.first() {
            let mut party = Party::from_data_row(&party_row.fields)?;
            party.last_modified_date = Some(Utc::now());
            
            let party_data = party.to_data_row();
            let update_conditions = vec![
                crate::models::QueryCondition {
                    field: "partyId".to_string(),
                    operator: "=".to_string(),
                    value: customer.party_id.clone(),
                    logic: "AND".to_string(),
                },
            ];
            
            self.client.update_data("Party", party_data, update_conditions).await?;
        }
        
        // 根据客户类型更新详细信息
        match customer.customer_type {
            CustomerType::Individual => {
                if let (Some(first_name), Some(last_name)) = (&customer.first_name, &customer.last_name) {
                    let person_query = QueryBuilder::new()
                        .eq("partyId", &customer.party_id)
                        .build();
                    
                    let person_response = self.client.query_data(
                        "Person",
                        None,
                        Some(person_query.conditions),
                        None,
                        person_query.limit,
                        person_query.offset
                    ).await?;
                    
                    if let Some(person_row) = person_response.first() {
                        let mut person = Person::from_data_row(&person_row.fields)?;
                        person.first_name = Some(first_name.clone());
                        person.last_name = Some(last_name.clone());
                        
                        let person_data = person.to_data_row();
                        let update_conditions = vec![
                            crate::models::QueryCondition {
                                field: "partyId".to_string(),
                                operator: "=".to_string(),
                                value: customer.party_id.clone(),
                                logic: "AND".to_string(),
                            },
                        ];
                        
                        self.client.update_data("Person", person_data, update_conditions).await?;
                    }
                }
            },
            CustomerType::Business => {
                if let Some(company_name) = &customer.company_name {
                    let group_query = QueryBuilder::new()
                        .eq("partyId", &customer.party_id)
                        .build();
                    
                    let group_response = self.client.query_data(
                        "PartyGroup",
                        None,
                        Some(group_query.conditions),
                        None,
                        group_query.limit,
                        group_query.offset
                    ).await?;
                    
                    if let Some(group_row) = group_response.first() {
                        let mut party_group = PartyGroup::from_data_row(&group_row.fields)?;
                        party_group.group_name = Some(company_name.clone());
                        party_group.annual_revenue = customer.annual_revenue;
                        party_group.num_employees = customer.num_employees;
                        
                        let group_data = party_group.to_data_row();
                        let update_conditions = vec![
                            crate::models::QueryCondition {
                                field: "partyId".to_string(),
                                operator: "=".to_string(),
                                value: customer.party_id.clone(),
                                logic: "AND".to_string(),
                            },
                        ];
                        
                        self.client.update_data("PartyGroup", group_data, update_conditions).await?;
                    }
                }
            }
        }
        
        Ok(())
    }
}

impl std::fmt::Display for CustomerType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CustomerType::Individual => write!(f, "Individual"),
            CustomerType::Business => write!(f, "Business"),
        }
    }
}

impl std::fmt::Display for CustomerStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CustomerStatus::Prospect => write!(f, "Prospect"),
            CustomerStatus::Lead => write!(f, "Lead"),
            CustomerStatus::Active => write!(f, "Active"),
            CustomerStatus::Inactive => write!(f, "Inactive"),
            CustomerStatus::Lost => write!(f, "Lost"),
        }
    }
}